﻿#region 文件信息

/*===================================================
* 类名称: VampirewalValidationService
* 类描述:
* 创建人: YangCheng
* 创建时间: 2022/5/21 13:56:19
* 修改人:
* 修改时间:
* 版本： @version 1.0
=====================================================*/

#endregion

namespace Vampirewal.Core.Components;

/// <summary>
/// VampirewalCore错误属性验证服务
/// <para>需要验证的类，属性上需要有<typeparamref name="ValidationAttribute特性"/></para>
/// </summary>
public sealed class VampirewalCoreValidationService : IVampirewalCoreValidationService
{
    /// <summary>
    /// 
    /// </summary>
    public VampirewalCoreValidationService()
    {
        ErrorList = new List<string>();
    }

    /// <summary>
    ///
    /// </summary>
    public List<string> ErrorList { get; private set; }

    /// <summary>
    /// 错误验证(传入需要验证的对象)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <returns></returns>
    public bool IsValidation<T>(T t) where T : class
    {
        ErrorList.Clear();

        var type = typeof(T);
        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            var attrs = property.GetCustomAttributes(typeof(ValidationAttribute), true);
            if (attrs.Length > 0)
            {
                foreach (var attr in attrs)
                {
                    var validation = attr as ValidationAttribute;
                    if (!validation.IsValid(property.GetValue(t)))
                    {
                        ErrorList.Add(string.IsNullOrEmpty(validation.ErrorMessage) ? $"{property.Name} 未填写错误信息!" : validation.ErrorMessage);
                    }
                }
            }
        }

        if (ErrorList.Count > 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}